<script>
  layui.config({
    base: '/static/customAdmin/',
  }).extend({
    index: 'lib/index',
  }).use(['index', 'form', 'admin', 'table', 'AutoComplete'], async () => {
    const { form, admin, table, $ } = layui;
    let annotation_item_data_filter = []
        , annotation_id = @{{.m.Id}}
        , impexpMarkcd = @{{.m.ImpexpMarkcd }} ? @{{.m.ImpexpMarkcd }} : @{{.ImpexpMarkcd }}
      , order_note_data /**附注数据**/
      , annotationItems /**清单表体数据**/
      , decListData = [] /**默认报关单数据**/
      , AnnotationSearcIndex;

    //基础参数版本
    await admin.getClearanceData();
    /**商品快速查询index**/
    await admin.clearance_data_auto([
      'list_types',
      'types_transfer',
      'modf_markcd_list',
      'finished_product',
      'nuclear_declaration_lis',
      'gen_dec_flag_list',
      'customs_declaration_type',
      'type_declaration_list',
      'two_account_manual',
      'ann_exempting_method',//4
      'ann_mode_shipping',//3
      'ann_objectives_based',//5
      'ann_entry_clearance',//1
      'ann_country_area',//9
      'ann_currency',//19
      'ann_unit_measurement',//23
    ]);

    //禁用表体 tab 点击
    if (!annotation_id) {
      let $annotationItemTab = $('#annotation_item_tab');
      $annotationItemTab.click(function (event) {
        return false
      })
    }
    /**根据屏幕等比例缩小**/
    admin.sideFlexible_window();
    /**回车键光标跳转**/
    admin.keydown_input_textarea();
    /**首次进入自动聚焦 and 初始数据赋值**/
    const first_name = $('#InvtTypeName').val();
    $('#InvtTypeName').val('').focus().val(first_name);
    $('#InputTime').val(admin.getCurrDate());
    $('#InvtDclTime').val(admin.getCurrDate());

    /**清单产品/报关草稿列表**/
    annotationItems = await admin.post('/annotation_item/datagrid', JSON.stringify({
      AnnotationId: parseInt(
        annotation_id),
    }), true)
    admin.getAnnotationTable(annotationItems, []);
    /**光标进入全选**/
    $('body').on('focus', 'input,textarea', function (e) {
      $(this).select();
      let tipText = '';
      for (let item of admin.tipsJson) {
        if (item.id === this.id) {
          tipText = item.name;
          break
        }
      }
      $('#tipsMessagetext').text(tipText)
    });
    /**table点击行选中**/
    admin.table_radio_click();
    /**table左右拖动**/
    admin.table_mousedown();
    /**备注回车保存商品**/
    $('body').on('keyup', '#BodyRmk', function (event) {
      const eCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode
      if (event.shiftKey !== 1 && eCode === 13) {
        $('#order_pros_submit').click()
      }
    })

    /**保存商品**/
    const annotation_item_data = async (data) => {
      /**集报不允许新增**/
      if (($('#InvtType').val() === '1' || $('#InvtType').val() === '8')
        && data.GdsSeqno > annotationItems.length) {
        layer.open({
          title: '提示',
          content: '当前清单类型不允许新增！',
          icon: 2,
        })
        return
      }

      let _row = {}
      $.extend(_row, annotationItems[data.GdsSeqno - 1])
      if (_row && _row.GdsSeqno && _row.GdsSeqno !== data.GdsSeqno) {
        layer.open({
          title: '提示',
          content: '表体序号不能修改！',
          icon: 2,
        })
        return
      }

      /*保存表体*/
      let result
      if (data.Id) {
        data.AnnotationId = "annotation_id"
        result = await admin.patch('/annotation_item/update/' + data.Id, data)
      } else {
        result = await admin.post('/annotation_item/store/' + annotation_id, data)
      }

      if (result.status) {
        await transformAnnotationItemsTable(result.obj.Annotation.Id, data)
      }

    }

    form.on('submit(order_pros_submit)', function (form) {
      if (annotationItems.rows.length > 1) {
        if (form.field.DclCurrcd !== annotationItems.rows[0].DclCurrcd) {
          return layer.msg('币制不一致！')
        }
      }

      if (form.field.Gdecd.toString().length !== 10) {
        return layer.msg('商品编号必须为10位！')
      }

      annotation_item_data(form.field)/*加载表体数据*/
    })

    /**商品--点击行反填数据**/
    table.on('row(order_pros)', function (obj) {
      for (let item in obj.data) {
        let id = item
        if (item === 'Rmk') {
          id = 'Body' + item
        } else if (item === 'Id') {
          id = 'AnnotationItem' + item
        }
        //赋值
        $(`#${id}`).val(obj.data[item])
        $(`#${id}`).removeClass('is_check_fail')
      }

      for (let item in obj.data) {
        let id = item
        if (item === 'Rmk') {
          id = 'Body' + item
        } else if (item === 'Id') {
          id = 'AnnotationItem' + item
        }
        //有错误显示错误
        let itemRecheckErrorInputIds = JSON.parse(`@{{ .m.ItemRecheckErrorInputIds}}`)
        for (let i in itemRecheckErrorInputIds) {
          let itemRecheckErrorInputIdElement = itemRecheckErrorInputIds[i][obj.data['GdsSeqno']]
          if ($.inArray(item, itemRecheckErrorInputIdElement) >= 0) {
            $(`#${id}`).addClass('is_check_fail')
          }
        }
      }
    })

    /**批量修改表体*/
    layui.form.on('submit(batch_edit_save)', async (data) => {
      let result = await admin.patch('/annotation_item_update/' + annotation_id, data.field)
      if (result.status) {
        setTimeout(function () {
          window.location.reload()
        }, 150)
      }
    })

    /**商品列表--按钮操作**/
    table.on('toolbar(order_pros)', async function (obj) {
      let checkStatus = table.checkStatus(obj.config.id)
      let checkData = checkStatus.data
      switch (obj.event) {
        case 'add':
          order_pros_form_focus()
          break
        case 'delete':
          if (checkData.length === 0) {
            return layer.msg('请选择数据')
          }
          layer.confirm('真的删除么', {
            title: '提示',
          }, async (index) => {
            if (checkData[0].Id) {
              let result = await admin.delete('/annotation_item/delete/' + checkData[0].Id)
              if (result.status) {
                await transformAnnotationItemsTable(annotation_id, '')
              }
            }
            layer.close(index)
          })
          break
        case 'copy':

          if (checkData.length === 0) {
            return layer.msg('请选择数据')
          }

          if (checkData.length !== 1) {
            return layer.msg('只能选择一条数据复制')
          }

          if (annotationItems.rows.length == 50) {
            layer.open({
              title: '提示',
              content: '本保税清单对应的报关单表体已经50条(不可超过50条)，请确认后重新录入！',
              icon: 2,
            })
            return
          }

          checkData[0].GdsSeqno = annotationItems.total + 1
          if (checkData[0].Id) {
            delete checkData[0].Id
          }

          await annotation_item_data(checkData[0])
          $(`.layui-table-view[lay-id='order_pros'] .layui-table-body tr[data-index=${annotationItems.total - 1}]`).click();

          break
        case 'batch_edit':
          if (annotationItems.total === 0) {
            return layer.msg('没有数据！')
          }

          layui.laytpl($('#batch_edit_list').html()).render(impexpMarkcd, function (html) {
            layer.open({
              type: 1,
              title: '商品批量修改',
              shadeClose: true,
              area: admin.screen() < 2 ? ['80%', '300px'] : ['680px', 'auto'],
              content: html,
            })
          })

          $('#DclCurrcdNameBatch').focus()

          /**最终目的国(地区)*/
          let destination_natcd = {
            name: '国别地区代码',
            filter_type: 'anns',
            id: ['#DestinationNatcdNameBatch'],
            after: ['#DestinationNatcdBatch'],
          }
          await admin.base_clearance_data_auto(destination_natcd)

          /**原产国（地区）*/
          let list_types = {
            name: '国别地区代码',
            filter_type: 'anns',
            id: ['#NatcdNameBatch'],
            after: ['#NatcdBatch'],
          }
          await admin.base_clearance_data_auto(list_types)

          /**自动完成--币制**/
          let dcl_currcd = {
            name: '货币代码',
            filter_type: 'anns',
            id: ['#DclCurrcdNameBatch'],
            after: ['#DclCurrcdBatch'],
          }
          await admin.base_clearance_data_auto(dcl_currcd)
          break

        case 'search':
          if (!@{{.m.HandBookId}}) {
            return layer.msg('手(账)册编号不能为空')
          }

          AnnotationSearcIndex = layer.open({
            type: 1,
            title: '商品快速查询',
            shadeClose: true,
            area: admin.screen() < 2 ? ['80%', '300px'] : ['950px', '540px'],
            content: $('#annotation_search_template').html(),
          });

          $('#gds_mtno_filter').focus();

          table.render({
            elem: '#annotation_search_table',
            defaultToolbar: ['filter'],
            colFilterRecord: 'local',
            cols: [
              [
                {
                  type: 'radio',
                }, {
                field: 'Serial',
                title: '备案序号',
                width: 100,
              }, {
                field: 'RecordNo',
                title: '商品料号',
                width: 140,
              }, {
                field: 'HsCode',
                title: '商品编码',
                width: 140,
              }, {
                field: 'Name',
                title: '商品名称',
                width: 240,
              }, {
                field: 'Special',
                title: '规格型号',
                width: 240,
              }, {
                field: 'UnitOne',
                title: '申报计量单位',
                width: 130,
              }, {
                field: 'UnitTwo',
                title: '法定计量单位',
                width: 130,
              }, {
                field: 'UnitThree',
                title: '法定第二计量单位',
                width: 160,
              }, {
                field: 'FstSfVal',
                title: '第一比例因子',
                width: 140,
              }, {
                field: 'SecdSfVal',
                title: '第二比例因子',
                width: 140,
              }],
            ],
            data: annotation_item_data_filter,
            limit: annotation_item_data_filter.length,
            height: 370,
          })
          break
      }
    })

    /**商品快速查询--查询**/
    form.on('submit(order_search_filter)', (data) => {
      let search_not = 0
      for (let item in data.field) {
        if (data.field[item].trim()) {
          search_not = 1
        }
      }
      if (!search_not) {
        return layer.msg('查询条件不能为空')
      }

      let data_search = get_ann_goods_materials_data(impexpMarkcd);
      const condition = {
        RecordNo: data.field.gds_mtno_filter,
        HsCode: data.field.gdecd_filter,
        Name: data.field.gds_nm_filter,
      }
      const data_filter = (condition, data) => {
        return data.filter(item => {
          return Object.keys(condition).every(key => {
            return String(item[key]).toLowerCase().includes(
              String(condition[key]).trim().toLowerCase())
          })
        })
      }
      annotation_item_data_filter = data_filter(condition, data_search);
      table.reload('annotation_search_table', {
        data: annotation_item_data_filter,
        limit: annotation_item_data_filter.length,
      })
    })

    /**商品快速查询--保存反填**/
    $('body').on('click', '#annotation_search_save', function () {
      const checkData = table.checkStatus('annotation_search_table').data
      if (checkData.length === 0) {
        return layer.msg('请选择')
      }
      $('#PutrecSeqno').val(checkData[0].Serial)
      $('#GdsMtno').val(checkData[0].RecordNo)
      $('#Gdecd').val(checkData[0].HsCode)
      $('#GdsNm').val(checkData[0].Name)
      $('#GdsSpcfModelDesc').val(checkData[0].Special)

      $('#DclUnitcd').val(checkData[0].UnitOneCode)
      $('#DclUnitcdName').val(checkData[0].UnitOne)

      $('#DclUprcAmt').val(checkData[0].Price)

      $('#LawfUnitcd').val(checkData[0].UnitTwoCode)
      $('#LawfUnitcdName').val(checkData[0].UnitTwo)

      $('#Natcd').val(checkData[0].ManuplaceCode)
      $('#NatcdName').val(checkData[0].Manuplace)

      $('#EntryGdsSeqno').focus()

      layer.close(AnnotationSearcIndex)
    })

    /**进口清单保存**/
    $('body').on('click', '#order_save', function () {
      $('#annotation_save').click()
    })
    form.on('submit(annotation_save)', async (data) => {
      layer.load(2)
      /**表体商品数据**/
      data.field.ImpexpMarkcd = "@{{.ImpexpMarkcd}}"
      if (@{{ .m.Id }}) {
        const annotation_data = await admin.patch('/annotation/update/' + @{{ .m.Id }}, data.field)
        if (annotation_data.status) {
          setTimeout(() => {
            window.location.reload()
          }, 300)

        }
      } else {
        const annotation_data = await admin.post('/annotation/store/' + @{{ .ImpexpMarkcd }}, data.field)
        if (annotation_data.status) {
          setTimeout(() => {
            window.location.href = '/annotation/edit/' + annotation_data.obj.Id
          }, 300)

        }
      }
      layer.closeAll('loading')
    })
    /**派单**/
    admin.distribute('#order_dispatch', annotation_id, "@{{.ImpexpMarkcdName}}" + '核注清单iframe',"annotation")
    /**附注**/
    let order_note_index
    let extraRemark = "@{{.m.ExtraRemark}}"
    $('body').on('click', '#order_note', async function () {
      if (!annotation_id) {
        return layer.msg('请先保存订单！')
      }
      order_note_index = layer.open({
        type: 1,
        title: '附注',
        shadeClose: true,
        area: admin.screen() < 2 ? ['80%', '300px'] : ['650px', '340px'],
        content: $('#remark_note_template').html(),
      })
      form.render()
      if (extraRemark) {
        $('#remark_note').val(extraRemark)
      }
    })
    if (extraRemark) {
      $('#order_note_dot').show()
    }
    $('body').on('input', '#remark_note', function () {
      $('#remark_note_number span').text($(this).val().length)
    })
    /**附注保存**/
    form.on('submit(remark_note_submit)', async (data) => {
      order_note_data = data.field.ExtraRemark
      await admin.post(`/annotation/extra_remark/${annotation_id}`, data.field)
      layer.close(order_note_index)
    })
    /**审核通过**/
    $('body').on('click', '#order_save_pass', function () {
      $('#annotation_save_pass').click()
    })

    form.on('submit(annotation_save_pass)', async () => {
      layer.load(2)
      let result = await admin.get(`/annotation/audit/` + annotation_id)
      if (result.status) {
        admin.reloadFrame("@{{.ImpexpMarkcdName}}" + '核注清单iframe')
        setTimeout(() => {
          window.location.reload()
        }, 150)
      }
      layer.closeAll('loading')
    })

    /**打印**/
    $('body').on('click', '#order_print', async function () {
      if (!annotation_id) {
        return layer.msg('请先保存订单！')
      }

      let url = await admin.get(`/annotation/print/${annotation_id}`)
      if (url) {
        window.open(url, '打印清单')
      }
    })

    /**申请复核**/
    $('body').on('click', '#annotaiton_for_recheck', function () {
      $('#annotation_application_review').click()
    })

    form.on('submit(annotation_application_review)', async (data) => {
      if (annotationItems.total === 0) {
        return layer.msg('请先输入表体商品')
      }
      layer.load(2)
      const result = await admin.get(`/annotation/for_recheck/${annotation_id}`, 'show')
      if (result.status) {
        admin.reloadFrame("@{{.ImpexpMarkcdName}}" + '核注清单iframe')
        setTimeout(() => {
          window.location.reload()
        }, 150)
      }

      layer.closeAll('loading')
    })

    /**重新申请复核**/
    $('body').on('click', '#annotation_refor_recheck', function () {
      $('#annotation_application_rereview').click()
    })

    form.on('submit(annotation_application_rereview)', async (data) => {
      if (annotationItems.total === 0) {
        return layer.msg('请先输入表体商品')
      }
      layer.load(2)
      const result = await admin.get(`/annotation/refor_recheck/${annotation_id}`, 'show')
      if (result.status) {
        admin.reloadFrame("@{{.ImpexpMarkcdName}}" + '核注清单iframe')
        setTimeout(() => {
          window.location.reload()
        }, 150)
      }

      layer.closeAll('loading')
    })

    /**表单验证规则**/
    await form.verify({})

    /**置空表单，定位焦点*/
    function order_pros_form_focus () {
      $('#order_pros_form input').each(function () {
        if ($(this).attr('id') === 'GdsSeqno') {
          $(this).val(annotationItems.total + 1)
        } else {
          if (!($(this).is('[no_empty]'))) {
            $(this).val('')
          }
        }
      })
      $('#putrec_seqno').focus()
    }

    /**加载表体表格*/
    async function transformAnnotationItemsTable (id, data) {
      let data1 = JSON.stringify({ AnnotationId: parseInt(id) })
      annotationItems = await admin.post('/annotation_item/datagrid', data1, true)
      /**加载清单产品/报关草稿表格列表**/
      admin.getAnnotationTable(annotationItems, decListData)
      order_pros_form_focus()
    }

  })
</script>